//
//  HttpUploadManager.m
//  HttpAPIRequest
//
//  Created by admin on 2019/5/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "HttpUploadManager.h"
#import "HttpResponse.h"
#import <AFNetworking/AFNetworking.h>
#import <YYModel/YYModel.h>

@interface HttpUploadManager ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation HttpUploadManager

- (instancetype)init{
    if (self = [super init]){
        [self initManager];
    }
    return self;
}


- (void)initManager{
    
    AFHTTPSessionManager* _manager = [AFHTTPSessionManager manager];
    
    ///config
    NSURLSessionConfiguration* _config = _manager.session.configuration;
    _config.timeoutIntervalForRequest = 10.f;
    _config.timeoutIntervalForResource = 10.f;
    _config.requestCachePolicy  = NSURLRequestReturnCacheDataElseLoad;
    _config.HTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    ///request
    
    AFHTTPRequestSerializer* requestSerializer = [AFHTTPRequestSerializer serializer];
    _manager.requestSerializer = requestSerializer;
    
    ///response
    AFJSONResponseSerializer* responseSerializer = [AFJSONResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"image/jpeg", nil];
    _manager.responseSerializer = responseSerializer;
    
    
    ///securityPolicy
    AFSecurityPolicy* securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    _manager.securityPolicy = securityPolicy;
    
    self.manager = _manager;
}

#pragma mark -------------------- public --------------------

+ (instancetype)sharedInstance
{
    static HttpUploadManager *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)setRequestHeader:(NSDictionary *)requestHeader{
    
    if(requestHeader.count){
        [requestHeader enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [self.manager.requestSerializer setValue:obj forHTTPHeaderField:key];
        }];
    }
}

- (void)upload:(NSString *)url params:(NSDictionary *)params fileConfigs:(NSArray<HttpUploadFile *> *)fileConfigs response:(Class)responseClass callback:(HttpResponseBlock)callback{
    
    [self.manager POST:url parameters:params headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (fileConfigs){
            for (int i = 0; i < [fileConfigs count]; i ++)
            {
                HttpUploadFile *fileConfig = [fileConfigs objectAtIndex:i];
                [formData appendPartWithFileData:fileConfig.fileData name:fileConfig.name fileName:fileConfig.fileName mimeType:fileConfig.mimeType];
            }
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
#ifdef DEBUG
        NSLog(@"request:%@->response:%@", url, responseObject);
#endif
        HttpResponse* response = [HttpResponse yy_modelWithJSON:responseObject];
        if(responseClass){
            id data = responseObject[@"data"];
            if([data isKindOfClass:[NSArray class]]){
                response.data = [NSArray yy_modelArrayWithClass:responseClass json:data];
            }else{
                response.data = [responseClass yy_modelWithJSON:data];
            }
        }
        if (callback){
            callback(response);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        HttpResponse* response = [HttpResponse new];
        response.code = error.code;
        response.message = @"请求失败，请稍后重试";
        response.data = nil;
        if (callback){
            callback(response);
        }
    }];
}

@end
